<template>

	<view>
		<view class="uni-header">
			<uni-stat-breadcrumb class="uni-stat-breadcrumb-on-phone" />
			<view class="uni-group">
				<button class="uni-button" type="warn" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">{{ $t('common.button.batchDelete') }}</button>
				<button class="uni-button" type="primary" size="mini" @click="openProductSelector">选择货品</button>
				<!-- 	<button class="uni-button" type="primary" size="mini"
					@click="navigateTo('./add?order_id='+order_id)">{{ $t('common.button.add') }}</button> -->


				<button @click="moreTable" class="uni-button" type="primary" size="mini"
					:disabled="!selectedIndexs.length">批量操作</button>
				<text>操作类别：</text>
				<button @click="current=0" :disabled="current==0" class="uni-button" size="mini">发货</button>
				<button @click="current=1" :disabled="current==1" class="uni-button" size="mini">已开票</button>

				<input class="uni-search" type="text" v-model="query" @confirm="search"
					:placeholder="$t('common.placeholder.query')" />
				<button class="uni-button hide-on-phone" type="default" size="mini"
					@click="search">{{ $t('common.button.search') }}</button>
				<!-- 导入文件 -->
				<!-- <button class="uni-button" type="primary" @click="chooseFile" size="mini">导入</button> -->
				<download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData"
					:type="exportExcel.type" :name="exportExcel.filename">
					<button class="uni-button" type="primary" size="mini">{{$t('common.button.exportExcel')}}</button>
				</download-excel>
			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList" :options="options" :where="where" page-data="replace"
				:orderby="orderby" :getcount="true" :page-size="options.pageSize" :page-current="options.pageCurrent"
				v-slot:default="{ data, pagination, loading, error, options }" @load="onqueryload">

				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">

					<!-- 订单信息列 -->
					<uni-tr>
						<uni-th align="center" width="50">序号</uni-th>
						<uni-th align="center" width="120">订单号</uni-th>
						<uni-th align="center" width="120">货品编码</uni-th>
						<uni-th align="center" width="220">货品名称</uni-th>
						<uni-th align="center">规格</uni-th>
						<uni-th align="center" width="100">单位</uni-th>
						<uni-th align="center" width="100">数量</uni-th>
						<uni-th align="center" width="100">已发数量</uni-th>
						<uni-th align="center" width="80">货位</uni-th>
						<uni-th align="center" width="120">订单详情状态</uni-th>
						<uni-th align="center" width="120">是否开票</uni-th>
						<uni-th align="center" width="100">MOQ</uni-th>
						<uni-th align="center" width="100">未税单价</uni-th>
						<uni-th align="center" width="100">税率</uni-th>
						<uni-th align="center" width="100">税额</uni-th>
						<uni-th align="center" width="100">金额</uni-th>
						<uni-th align="center" width="100">已销售数量</uni-th>
						<uni-th align="center" width="100">是否为赠品</uni-th>
						<uni-th align="center" width="120">发货日期</uni-th>
						<uni-th align="center" width="100">订单行号</uni-th>
						<uni-th align="center" width="150">内部特殊备注</uni-th>
						<uni-th align="center" width="150">原供应商PN</uni-th>
						<uni-th align="center" width="200">产品中文描述</uni-th>
						<uni-th align="center" width="100">版本号PC</uni-th>
						<uni-th align="center" width="120">清洗类型</uni-th>
						<uni-th align="center" width="100">清洗单价</uni-th>
						<uni-th align="center" width="100">未税价</uni-th>
						<uni-th align="center" width="150">备注</uni-th>

						<uni-th align="center" width="100">发票号</uni-th>
						<uni-th align="center" width="180">开票日期</uni-th>
						<uni-th align="center" width="150">操作</uni-th>
					</uni-tr>

					<uni-tr v-for="(item, index) in data" :key="index">
						<uni-td align="center">{{ index + 1 }}</uni-td>
						<uni-td align="center">{{ orders_number }} </uni-td>
						<uni-td align="center">{{ item.product_code }}</uni-td>
						<uni-td align="center">{{ item.product_name }}</uni-td>
						<uni-td align="center">{{ item.specification }}</uni-td>
						<uni-td align="center">{{ item.unit }}</uni-td>
						<uni-td align="center">
							<text @dblclick="enableEditYf(item)"
								style="cursor: pointer;">{{ item.quantity || 0 }}</text>
							<input v-if="item.editingYf" style="border: 1px solid;" type="number"
								v-model="item.newQuantityYf" @blur="updateQuantityYf(item)"
								@keyup.enter="updateQuantityYf(item)" />
						</uni-td>
						<uni-td align="center">
							<text @dblclick="enableEdit(item)"
								style="cursor: pointer;">{{ item.yf_quantity || 0 }}</text>
							<input v-if="item.editing" style="border: 1px solid;" type="number"
								v-model="item.newQuantity" @blur="updateQuantity(item)"
								@keyup.enter="updateQuantity(item)" />
						</uni-td>
						<uni-td align="center">{{ item.position }}</uni-td>
						<uni-td align="center">
							<text v-if="item.status == 0" style="color: green;">配货</text>
							<text v-if="item.status == 1" style="color: skyblue;">清洗中</text>
							<text v-if="item.status == 2" style="color: orange;">已发货</text>
							<text v-if="item.status == 3" style="color: #e43d33;">终止</text>
						</uni-td>

						<uni-td align="center">
							<text v-if="!item.is_kp" style="color: green;">未开票</text>
							<text v-else style="color: #e43d33;">已开票</text>
						</uni-td>
						<uni-td align="center">{{ item.moq }}</uni-td>
						<uni-td align="center">{{ item.unit_price_excl_tax }}</uni-td>
						<uni-td align="center">{{ item.tax_rate }}</uni-td>
						<uni-td align="center">{{ Number(item.tax_amount).toFixed(2) }}</uni-td>
						<uni-td align="center">{{ Number(item.amount).toFixed(2)  }}</uni-td>

						<uni-td align="center">{{ item.quantity_sold }}</uni-td>
						<uni-td align="center">{{ item.gift ? '是' : '否' }}</uni-td>
						<uni-td align="center">{{ item.delivery_date }}</uni-td>
						<uni-td align="center">
							<text @dblclick="enableEditDd(item)"
								style="cursor: pointer;">{{ item.order_line_number || 0 }}</text>
							<input v-if="item.editingDd" style="border: 1px solid;" type="number"
								v-model="item.newQuantityDd" @blur="updateQuantityDd(item)"
								@keyup.enter="updateQuantityDd(item)" />
						</uni-td>
						<uni-td align="center">{{ item.internal_special_note }}</uni-td>
						<uni-td align="center">{{ item.supplier_PN }}</uni-td>
						<uni-td align="center">{{ item.goods_desc }}</uni-td>
						<uni-td align="center">{{ item.version }}</uni-td>
						<uni-td align="center">{{ item.cleaning_type }}</uni-td>
						<uni-td align="center">{{ item.qx_price }}</uni-td>
						<uni-td align="center">{{ Number(item.price_excl_tax).toFixed(2) }}</uni-td>
						<uni-td align="center">{{ item.additional_items }}</uni-td>

						<uni-td align="center">{{ item.kp_num }}</uni-td>
						<uni-td align="center">{{ $formatDate(item.kp_date)}}</uni-td>

						<uni-td align="center">
							<view class="uni-group">

								<text class="blue cu_po" style="margin-left: 5px;margin-right: 5px;"
									@click="navigateTo('./add?order_id='+order_id+'&id=' + item._id, false)">修改</text>
							</view>
						</uni-td>
					</uni-tr>


				</uni-table>

				<!-- 分页 -->
				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
			<!-- 选择货品弹窗 -->
			<uni-popup ref="popup" type="dialog" :mask-click="false">
				<view class="popup-content">
					<!-- 搜索框 -->
					<uni-easyinput placeholder="搜索货品" v-model="searchQuery" @input="filterProducts"></uni-easyinput>
					<!-- 货品列表 -->
					<view class="popup-content-b">
						<view class="popup-content-list" v-for="(product, index) in filteredProducts" :key="index"
							 @click="selectProduct(product)">
							<text>{{ product.goods_sn }}</text>
							<text style="margin-left: 10px; color: red;">{{ product.remain_count }}</text>
						</view>

					</view>
					<view class="t-c mar-t-15 ">
						<button class="mini-btn" @click="close" type="default" size="mini">关闭</button>
					</view>
				</view>

			</uni-popup>
			<uni-fab ref="fab" horizontal="right" vertical="bottom" :pop-menu="false" @fabClick="fabClick" />
		</view>
	</view>
</template>

<script>
	import * as XLSX from 'xlsx'
	const db = uniCloud.database()
	const dbCollectionName = 'order-text';
	// 表查询配置
	const dbOrderBy = 'create_date'; // 排序字段
	const dbSearchFields = ['product_code', 'product_name']; // 支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 5;
	const pageCurrent = 1;
	export default {
		data() {
			return {
				r1: '1',
				old: {},
				item: {},
				current: 0,
				orders_number: "",
				operationMessage: "请选择需要操作的项目", // 初始提示文字
				formData: {
					"kp_num": null,
					"kp_date": null,
					"is_kp": null,
					"status": 0,
					"order_id": "",
					"product_code": "",
					"product_name": "",
					"specification": "",
					"unit": "",
					"huoping_id": "",
					"quantity": 0,
					"qx_price": 0,
					"moq": null,
					"unit_price_excl_tax": null,
					"tax_rate": 0.13,
					"tax_amount": null,
					"amount": null,
					"quantity_sold": null,
					"gift": null,
					"delivery_date": null,
					"order_line_number": "",
					"internal_special_note": "",
					"supplier_PN": "",
					"goods_desc": "",
					"version": "",
					"cleaning_type": "",
					"qx_price": null,
					"price_excl_tax": null,
					"additional_items": "",
					"position": ""
				},
				remain_count: 0,
				pageCurrent:1,
				searchQuery: '', // 搜索框输入内容
				selectedCategory: 0, // 当前选择的类别
				categories: ['全部', '类别1', '类别2'], // 货品类别
				products: [],
				filteredProducts: [], // 筛选后的货品列表
				paginatedProducts: [], // 分页后的货品列表
				currentPage: 1, // 当前页码
				itemsPerPage: 10, // 每页显示数量
				hasMore: true,
				formOptions: {},
				options: {
					pageSize,
					pageCurrent
				},
				collectionList: "order-text",
				selectedIndexs: [],
				order_id: '',
				query: '',
				where: '_id=',
				orderby: dbOrderBy,
				exportExcelData: [],
				exportExcel: {
					"filename": "订单详情.xls",
					"type": "xls",
					"fields": {
						"订单号": "orders_number",
						"货品编码": "product_code",
						"货品名称": "product_name",
						"规格": "specification",
						"单位": "unit",
						"数量": "quantity",
						"MOQ": "moq",
						"折扣百分比": "discount",
						"未税单价": "unit_price_excl_tax",
						"税率": "tax_rate",
						"税额": "tax_amount",
						"金额": "amount",
						"已销售数量": "quantity_sold",
						"是否为赠品": "gift",
						"订单行号": "order_line_number",
						"内部特殊备注": "internal_special_note",
						"原供应商PN/misumi料号": "supplier_PN",
						"供应商代码": "supplier_code",
						"产品中文描述": "goods_desc",
						"版本号PC": "version",
						"清洗类型": "cleaning_type",
						"清洗单价": "qx_price",
						"未税价": "price_excl_tax",
						"货位": "position",
						"附项": "additional_items"


					}
				},
			}
		},
		onPullDownRefresh() {
			this.$refs.udb.loadData({
				clear: true
			}, () => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			this.$refs.udb.loadMore()
		},
		onLoad(e) {
			this.where = {
				'order_id': e.id
			}
			this.order_id = e.id
			this.orders_number = e.orders_number
			this.getInventory()
		},
		methods: {
			close() {
				this.$refs.popup.close()
			},
			openProductSelector() {
									
				this.isProductPopupVisible = true;
				this.filterProducts(); // 初始化筛选
				// 通过组件定义的ref调用uni-popup方法 ,如果传入参数 ，type 属性将失效 ，仅支持 ['top','left','bottom','right','center']
				this.$refs.popup.open('center')
			},
			filterProducts() {
				let products = this.products;
				// 先根据搜索框过滤
				if (this.searchQuery) {
					products = products.filter(product => product.goods_sn
						.includes(this.searchQuery));
				}

				// 然后根据选择的类别进行过滤
				if (this.selectedCategory > 0) {
					products = products.filter(product => product.category === this.categories[this
						.selectedCategory]);
				}

				this.filteredProducts = products;
				this.paginateProducts(); // 分页
			},
			filterByCategory() {
				this.filterProducts(); // 筛选时按类别过滤
			},
			paginateProducts() {
				const start = (this.currentPage - 1) * this.itemsPerPage;
				const end = this.currentPage * this.itemsPerPage;
				this.paginatedProducts = this.filteredProducts.slice(start, end);
				this.hasMore = this.filteredProducts.length > end; // 判断是否还有更多数据
			},
			loadMore() {
				this.currentPage += 1;
				this.paginateProducts(); // 加载更多
			},
			//添加数据
			selectProduct(product) {
				this.formData.order_id = this.order_id
				this.formData.product_name = product.name;
				this.formData.product_code = product.goods_sn;
				this.formData.goods_desc = product.goods_desc
				this.formData.qx_price = product.qx_price
				this.formData.moq = product.moq
				this.formData.specification = product.type;
				this.formData.unit = product.danwei;
				this.remain_count = product.remain_count
				this.formData.huoping_id = product._id
				this.formData.cleaning_type = product.qx_type
				this.formData.unit_price_excl_tax = product.shop_price
				this.formData.position = product.position
				// console.log(this.formData, 1234);
				this.item = product
				this.quantityInput(1, 1, 1) //第一个1是增加或者减少 第二个1是数量 第三个是增加或者修改
				this.isProductPopupVisible = false;
			},
			

			//获取库存商品
			async getInventory() {
				let products = []
				let offset = 0
				const batchSize = 1000

				while (true) {
					const result = await db.collection('opendb-mall-goods')
						.orderBy('add_date', 'desc')
						.skip(offset)
						.limit(batchSize)
						.get()
					// console.log(res);
					const res = result.result
					if (!res.data.length) break

					products = products.concat(res.data)
					offset += batchSize
				}
				this.products = products
				// console.log(this.products);
			},
			//数量修改
			quantityInput(e, type, editIs) {

				this.formData.quantity = e
				// 执行逻辑
				if (e > this.remain_count) {
					this.$set(this.formData, 'quantity', 0); // 确保是响应式更新
					console.log(this.formData.quantity);
					uni.showToast({
						title: '库存还有' + this.remain_count,
						duration: 2000,
						icon: 'none'
					});
				}
				this.formData.price_excl_tax = this.formData.unit_price_excl_tax * this.formData
					.quantity //未税价格
				this.formData.tax_amount = this.formData.price_excl_tax * 0.13 //税率
				this.formData.amount = this.formData.price_excl_tax + this.formData.tax_amount //销售金额
				this.subAdd(this.formData, type, editIs)

			},
			//提交修改
			subAdd(value, type, editIs) {
				 
				console.log(this.formData, 888, this.old.quantity);

				// 使用 clientDB 提交数据
				if (editIs == 1) {
					this.updateKucun(type, this.formData.quantity, this.formData.huoping_id)
					return db.collection(dbCollectionName).add(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '新增成功'
						})
						this.loadData();
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				} else {
					this.updateKucun(type, this.formData.quantity - this.old.quantity, this.formData.huoping_id)
					let value = {
						...this.formData
					};
					delete value.newQuantityYf;
					delete value.newQuantity;
					delete value.newQuantityDd;
					delete value.editingDd;
					delete value.editingYf;
					delete value.editing;
					delete value._id;
					// 使用 clientDB 提交数据
					return db.collection(dbCollectionName).doc(this.formData._id).update(value).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						})
						this.loadData()
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				}

			},

			// 进入编辑模式
			enableEditYf(item) {
				this.$set(item, 'editingYf', true); // 显示输入框
				this.$set(item, 'newQuantityYf', item.quantity); // 保存当前的数量，供修改
			},
			// 进入编辑模式
			enableEditDd(item) {
				this.$set(item, 'editingDd', true); // 显示输入框
				this.$set(item, 'newQuantityDd', item.order_line_number); // 保存当前的数量，供修改
			},
			// 更新订单行号
			updateQuantityDd(item) {

				if (item.newQuantityDd !== item.quantity) {
					this.updateDatabase(item._id, item.newQuantityDd, 2).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						})
						item.order_line_number = item.newQuantityDd; // 更新显示的数量
						this.$set(item, 'editingDd', false); // 退出编辑模式
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				} else {
					this.$set(item, 'editingDd', false); // 如果没有修改，直接退出编辑模式
				}

			},
			// 更新数量
			updateQuantityYf(item) {

				if (item.newQuantityYf !== item.quantity) {
					this.formData = {}
					this.formData = item
					this.old = {
						...item
					}
					//如果现在的数量大于原来的数量
					let num = item.newQuantityYf - item.quantity
					let type = 0
					if (num > 0) {
						type = 1
					} else if (num < 0) {
						type = 2
					}
					item.quantity = item.newQuantityYf; // 更新显示的数量
					let product = this.products.filter(res => res._id == this.formData.huoping_id) // 过滤出 id 匹配的元素
						.map(res => res);
					this.remain_count = product.remain_count
					this.item = product
					this.quantityInput(item.newQuantityYf, type, 2) //修改数量

				} else {
					this.$set(item, 'editingYf', false); // 如果没有修改，直接退出编辑模式
				}
			},
			// 进入编辑模式
			enableEdit(item) {
				this.$set(item, 'editing', true); // 显示输入框
				this.$set(item, 'newQuantity', item.yf_quantity); // 保存当前的数量，供修改
			},

			// 更新数量
			updateQuantity(item) {
				if (item.newQuantity !== item.yf_quantity) {
					this.updateDatabase(item._id, item.newQuantity, 2).then((res) => {
						uni.showToast({
							icon: 'none',
							title: '修改成功'
						})
						item.yf_quantity = item.newQuantity; // 更新显示的数量
						this.$set(item, 'editing', false); // 退出编辑模式
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})

				} else {
					this.$set(item, 'editing', false); // 如果没有修改，直接退出编辑模式
				}
			},
			// 修改已发数量
			updateDatabase(id, newQuantity, type) {
				if (type == 1) {

				} else {

					return db.collection("order-text").doc(id).update({
						yf_quantity: newQuantity
					})
				}

			},
			//添加数据
			addItem() {
				console.log(1234);
			},
			async daochu(id) {
				try {
					// 从数据库中获取订单数据
					const orderRes = await db.collection('orders').where({
						_id: id
					}).get();
					if (!orderRes.result.data || !orderRes.result.data.length) {
						throw new Error('订单数据获取失败');
					}
					const orderData = orderRes.result.data[0];

					// 从数据库中获取关联的货品数据
					const productRes = await db.collection('order-text').where({
						order_id: id
					}).get();
					if (!productRes.result.data) {
						throw new Error('货品数据获取失败');
					}
					const productData = productRes.result.data;

					// 定义中文字段名和英文字段名的映射关系
					const fieldMapping = {
						"订单号": "order_number",
						"客户名称": "customer_name",
						"结算方式": "settlement_method",
						"币种": "currency",
						"是否提醒采购": "reminder_for_purchase_order",
						"合同编号": "contract_number",
						"发货日期": "shipping_date",
						"预付款金额": "prepayment_amount",
						"订单状态": "order_status",
						"创建日期": "create_date"
					};

					const productFieldMapping = {
						"货品编码": "product_code",
						"货品名称": "product_name",
						"规格": "specification",
						"单位": "unit",
						"数量": "quantity",
						"MOQ": "moq",
						"折扣%": "discount",
						"未税单价": "unit_price_excl_tax",
						"税率": "tax_rate",
						"税额": "tax_amount",
						"金额": "amount",
						"已销售数量": "quantity_sold",
						"赠品": "gift",
						"发货日期": "delivery_date",
						"订单行号": "order_line_number",
						"内部特殊备注": "internal_special_note",
						"原供应商PN/misumi料号": "supplier_PN",
						"供应商代码": "supplier_code",
						"产品中文描述": "goods_desc",
						"版本号PC": "version",
						"清洗类型": "cleaning_type",
						"清洗单价": "qx_price",
						"未税价": "price_excl_tax",
						"货位": "position",
						"附项": "additional_items"
					};

					// 转换订单数据和货品数据的字段名为中文
					const orderDataWithChineseFields = Object.keys(orderData).reduce((result, key) => {
						const chineseKey = Object.keys(fieldMapping).find(chinese => fieldMapping[
								chinese] ===
							key);
						if (chineseKey) {
							result[chineseKey] = orderData[key];
						}
						return result;
					}, {});

					const productDataWithChineseFields = productData.map(product => {
						return Object.keys(product).reduce((result, key) => {
							const chineseKey = Object.keys(productFieldMapping).find(chinese =>
								productFieldMapping[chinese] === key);
							if (chineseKey) {
								result[chineseKey] = product[key];
							}
							return result;
						}, {});
					});

					// 获取表头
					const orderDataHeaders = Object.keys(fieldMapping).map(chinese => chinese);
					const productDataHeaders = Object.keys(productFieldMapping).map(chinese => chinese);

					// 构建最终数据：先是订单数据，后插入空行，再是货品数据
					const finalData = [
						// 订单表头
						orderDataHeaders,
						// 订单数据
						Object.values(orderDataWithChineseFields),
						// 空行
						[],
						// 货品表头
						productDataHeaders,
						// 货品数据
						...productDataWithChineseFields.map(product => Object.values(product))
					];

					// 使用 XLSX.utils.aoa_to_sheet 生成工作表
					const ws = XLSX.utils.aoa_to_sheet(finalData);

					// 创建工作簿并导出
					const wb = XLSX.utils.book_new();
					XLSX.utils.book_append_sheet(wb, ws, "订单和货品数据");

					// 动态文件名
					XLSX.writeFile(wb, `订单和货品数据_${id}.xlsx`);
				} catch (error) {
					console.error('导出失败:', error);
				}
			},
			onqueryload(data) {
				data.forEach(e => {
					e.orders_number = this.orders_number
				})
				this.exportExcelData = data
			},
			onPageChanged(e) {
				this.pageCurrent = e.current
				this.selectedIndexs.length = 0;
				this.$refs.table.clearSelection();
				this.$refs.udb.loadData({
					current: e.current
				});
			},
			getWhere() {
				const query = this.query.trim();
				if (!query) {
					return '';
				}
				let queryRe;
				try {
					queryRe = new RegExp(query, 'i');
				} catch (err) {
					uni.showToast({
						title: '请勿输入\等不满足正则格式的符号',
						icon: 'none'
					});
					return;
				}
				// 生成查询条件
				let queryConditions = dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ');
				queryConditions = `(${queryConditions}) && (order_id == '${this.order_id}')`;

				return queryConditions;
			},
			search() {
				const newWhere = this.getWhere();
				const isSameWhere = newWhere === this.where;
				this.where = newWhere;
				if (this.query == '') {
					this.where = {
						'order_id': this.order_id
					}
				}
				if (isSameWhere) {
					// 相同条件时，手动强制刷新
					this.loadData();
				}
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					current: this.pageCurrent
				});
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList;
				console.log(dataList);
				return this.selectedIndexs.map(i => dataList[i]._id);
			},
			//操作货品状态
			async moreTable() {
				let text = ''
				text = this.current == 0 ? '发货' : '已开票'
				const dataList = this.$refs.udb.dataList;
				const datas = this.selectedIndexs
					.map(i => dataList[i])
				console.log(datas);
				try {
					uni.showModal({
						title: '温馨提示',
						content: `是否批量${text}？`,
						success: async (res) => {
							if (res.confirm) {
								// 使用 Promise.all 并行执行所有更新操作
								await Promise.all(datas.map(element => this
									.plUpdate(element._id)));
								this.$refs.table.clearSelection();
								uni.showToast({
									icon: 'none',
									title: '操作成功'
								})
								this.loadData()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});


				} catch (error) {
					uni.showToast({
						icon: 'none',
						title: '操作失败'
					})
					console.error('库存更新失败', error);
				}


			},
			// 删除并更新库存
			async delTable(e) {
				const dataList = this.$refs.udb.dataList;
				const datas = this.selectedIndexs
					.map(i => dataList[i])
					.filter(item => item.status < 2); // 筛选出 status < 2 的项
				try {
					//移除选中的项
					this.$refs.udb.remove(this.selectedItems(), {
						success: async (res) => {
							// 使用 Promise.all 并行执行所有更新操作
							await Promise.all(datas.map(element => this.updateKucuns(2, element)));
							this.$refs.table.clearSelection();
						}
					});
				} catch (error) {
					uni.showToast({
						icon: 'none',
						title: '库存更新失败'
					})
					console.error('库存更新失败', error);
				}
			},
			//修改库存数量
			async updateKucun(type, num, id) {
				console.log(type, num, id, this.formData);

				let ws = (this.formData.unit_price_excl_tax * num) * 0.13 + this.formData.unit_price_excl_tax *
					num //未税价格
				let data = {
					id, // 替换为你要更新库存的商品的 ID
					quantity: num * 1, // 传入你要增加的库存数量
					type, //增加或者修改
					order_id: this.formData.order_id,
					sale_price: ws

				}
				console.log(data);
				uniCloud.callFunction({
					name: 'update-kucun',
					data
				}).then(res => {
					// console.log(res);
					if (res.result.code === 200) {
						console.log('库存更新成功');
					} else {
						console.log('库存更新失败:', res.result.msg);
					}
				}).catch(err => {
					console.error('调用云函数失败', err);
				});
			},
			async plUpdate(id) {
				if (this.current == 0) {
					return db.collection("order-text").doc(id).update({
						status: 2
					})
				} else if (this.current == 1) {
					return db.collection("order-text").doc(id).update({
						is_kp: true
					})
				}

			},
			// 删除数据后 修改库存数量
			async updateKucuns(type, item) {
				let ws = (item.unit_price_excl_tax * item.quantity) * 0.13 + item.unit_price_excl_tax * item
					.quantity //未税价格
				const data = {
					id: item.huoping_id, // 商品 ID
					quantity: Number(item.quantity), // 库存数量
					type, // 操作类型
					order_id: item._id, // 订单 ID
					sale_price: ws
				};
				console.log(data);

				try {
					const res = await uniCloud.callFunction({
						name: 'update-kucun',
						data
					});

					if (res.result.code === 200) {
						console.log('库存更新成功');
					} else {
						console.log('库存更新失败:', res.result.msg);
					}
				} catch (err) {
					console.error('调用云函数失败', err);
				}
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index;
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: res => {
						this.$refs.table.clearSelection();
					}
				});
			},
			navigateTo(url) {
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			fabClick() {
				// 打开新增页面
				uni.navigateTo({
					url: './add',
					events: {
						// 监听新增数据成功后, 刷新当前页面数据
						refreshData: () => {
							this.$refs.udb.loadData({
								clear: true
							})
						}
					}
				})
			}
		}
	}
</script>

<style>
	.popup-content {
		background-color: #fff;
		width: 350px;
		height: 300px;
		padding: 15px;
	}

	.popup-content-b {
		height: calc(100% - 80px);
		overflow: auto;
		overflow-x: hidden;
	}

	.popup-content-list {
		border-top: 1px solid #ddd;
		/* 边框颜色为浅灰色 */
		padding: 8px 18px;
		/* 稍微增加内边距 */
		cursor: pointer;
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* 保证文字在垂直方向居中 */
		transition: all 0.3s ease;
		/* 添加过渡效果，使hover时变得更平滑 */
		border-radius: 8px;
		/* 圆角效果 */
		background-color: #f9f9f9;
		/* 初始背景色为浅灰色 */
		margin-bottom: 2px;
	}

	.popup-content-list:hover {
		opacity: 0.8;
		/* 提高透明度，增加悬停的立体感 */
		background-color: #f1f1f1;
		/* 浅灰色背景色 */
		color: #333;
		/* 悬停时文本颜色变为深灰色 */
		border-top: 1px solid #aaa;
		/* 增加更明显的边框颜色 */
		box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果，使元素浮动 */
		transform: scale(1.02);
		/* 鼠标悬停时微微放大，增加交互感 */
	}
</style>